package com.aliexpress.controller.business;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliexpress.bean.AttributeBean;
import com.aliexpress.bean.CategoryBean;
import com.aliexpress.bean.Result;
import com.aliexpress.constant.StaticConstants;
import com.aliexpress.constant.SysConstants;
import com.aliexpress.controller.common.BaseController;
import com.aliexpress.cookies.CookiesParse.ChromeBrowser;
import com.aliexpress.model.Menu;
import com.aliexpress.service.MenuService;

@Controller
@RequestMapping(value = "/menu")
public class MenuController extends BaseController {
	private static final Logger log = Logger.getLogger(MenuController.class);
	@Value("${cookies.path}")
	private String cookiesPath;
	@Autowired
	private MenuService service;

	@RequestMapping(value = "/menulist")
	public String welcome() throws Exception {
		return "business/menu/menulist";
	}

	@RequestMapping(value = "/menuform")
	public String menuform() throws Exception {
		return "business/menu/menuform";
	}

	@RequestMapping(value = "/menuselect")
	public String menuselect() throws Exception {
		return "business/menu/menuselect";
	}

	@RequestMapping(value = "/editTemplate")
	public String editTemplate() throws Exception {
		return "business/menu/editTemplate";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/category")
	public @ResponseBody Result category() {
		Result result = new Result();
		try {
			String json = queryData("https://www.dianxiaomi.com/smtCategory/list.json");
			log.info(json);
			if (StringUtils.isNotBlank(json)) {
				JSONArray array = JSONArray.fromObject(json);
				List<CategoryBean> list = (List<CategoryBean>) JSONArray.toCollection(array, CategoryBean.class);
				result.setCode(SysConstants.STATUS_TRUE);
				result.setMsg("查询目录成功！");
				result.setList(list);
			} else {
				result.setCode(SysConstants.STATUS_FALSE);
				result.setMsg("查询目录失败！");
			}
		} catch (Exception e) {
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg("查询目录异常！");
			e.printStackTrace();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/categorys/{pcid}")
	public @ResponseBody Result categorys(@PathVariable("pcid") String pcid) {
		Result result = new Result();
		try {
			String json = queryData("https://www.dianxiaomi.com/smtCategory/list.json?pcid=" + pcid);
			log.info(json);
			if (StringUtils.isNotBlank(json)) {
				JSONArray array = JSONArray.fromObject(json);
				List<CategoryBean> list = (List<CategoryBean>) JSONArray.toCollection(array, CategoryBean.class);
				result.setCode(SysConstants.STATUS_TRUE);
				result.setMsg("查询目录成功！");
				result.setList(list);
			} else {
				result.setCode(SysConstants.STATUS_FALSE);
				result.setMsg("查询目录失败！");
			}
		} catch (Exception e) {
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg("查询目录异常！");
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/attributeList/{categoryId}")
	public @ResponseBody Result attributeList(@PathVariable("categoryId") String categoryId) {
		Result result = new Result();
		try {
			String json = queryData("https://www.dianxiaomi.com/smtCategory/attributeList.json?categoryId=" + categoryId);
			// log.info(json);
			if (StringUtils.isNotBlank(json)) {
				JSONArray array = JSONArray.fromObject(json);
				JSONObject obj = null;
				AttributeBean bean = null;
				List<AttributeBean> list = new ArrayList<AttributeBean>();
				if (null != array) {
					for (int i = 0, a = array.size(); i < a; i++) {
						obj = array.getJSONObject(i);
						bean = new AttributeBean();
						bean.setId(obj.getLong("id"));
						bean.setCategoryId(obj.getLong("categoryId"));
						bean.setArrtNameId(obj.getInt("arrtNameId"));
						bean.setNameZh(obj.getString("nameZh"));
						bean.setNameEn(obj.getString("nameEn"));
						bean.setInputType(obj.getString("inputType"));
						bean.setAttributeShowTypeValue(obj.getString("attributeShowTypeValue"));
						bean.setRequired(obj.getInt("required"));
						bean.setValues(obj.getString("values"));
						list.add(bean);
					}
				}
				result.setCode(SysConstants.STATUS_TRUE);
				result.setMsg("查询产品属性成功！");
				result.setList(list);
			} else {
				result.setCode(SysConstants.STATUS_FALSE);
				result.setMsg("查询产品属性失败！");
			}
		} catch (Exception e) {
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg("查询产品属性异常！");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 查询菜单列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/showList", produces = "application/json;charset=utf-8")
	public @ResponseBody Result showList() {
		log.info("查询module数据");
		Result result = new Result();
		try {
			List<Menu> list = service.selectAllList();// 查询符合条件的数据
			result.setCode(SysConstants.STATUS_TRUE);
			result.setList(list);
		} catch (Exception e) {// 异常处理
			log.info(e.getMessage());
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/**
	 * 批量删除
	 * 
	 * @param keys
	 * @return
	 */
	@RequestMapping(value = "/deleteMenu", produces = "application/json;charset=utf-8")
	public @ResponseBody Result deleteMenu(@RequestParam(required = false, value = "keys") String keys) {
		log.info("主键：" + keys);
		Result result = new Result();
		try {
			if (StringUtils.isNotBlank(keys)) {
				List<Integer> keyes = new ArrayList<Integer>();
				String[] objs = keys.split(",");
				for (String k : objs) {
					keyes.add(Integer.valueOf(k));
				}
				int num = service.deleteMenuByKeys(keyes);
				if (num > 0) {
					result.setCode(SysConstants.STATUS_TRUE);
					result.setMsg("成功刪除" + num + "条数据");
				} else {
					result.setCode(SysConstants.STATUS_FALSE);
					result.setMsg("删除失败！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/**
	 * 根据ID查询数据
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/showUpdate", produces = "application/json;charset=utf-8")
	public @ResponseBody Result showUpdate(@RequestParam(required = false, value = "key") Integer id) {
		Result result = new Result();
		try {
			if (id != null) {
				Menu menu = service.selectByKey(id);
				result.setCode(SysConstants.STATUS_TRUE);
				result.setObject(menu);
			}
		} catch (Exception e) {
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg(e.getMessage());
			result.setObject(null);
		}
		return result;
	}

	@RequestMapping(value = "/addMenu", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody Result addMenu(Menu menu) {
		int num = 0;
		Result result = new Result();
		try {
			if (menu.getId() == null) {
				num = service.addMenu(menu);
				if (num > 0) {
					result.setCode(SysConstants.STATUS_TRUE);
					result.setMsg("添加成功~");
				} else {
					result.setCode(SysConstants.STATUS_FALSE);
					result.setMsg("添加失败！");
				}
			} else {
				num = service.updateMenu(menu);
				if (num > 0) {
					result.setCode(SysConstants.STATUS_TRUE);
					result.setMsg("修改成功~");
				} else {
					result.setCode(SysConstants.STATUS_FALSE);
					result.setMsg("修改失败！");
				}
			}
		} catch (Exception e) {
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg("保存异常！");
		}
		return result;
	}

	@RequestMapping(value = "/saveTemplate", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody Result saveTemplate(Menu menu) {
		Result result = new Result();
		try {
			log.info(menu.toString());
			if (menu.getId() != null) {
				int num = service.saveTemplate(menu);
				if (num > 0) {
					result.setCode(SysConstants.STATUS_TRUE);
					result.setMsg("保存成功~");
				} else {
					result.setCode(SysConstants.STATUS_FALSE);
					result.setMsg("保存失败！");
				}
			}
		} catch (Exception e) {
			result.setCode(SysConstants.STATUS_ERROR);
			result.setMsg("保存异常！");
		}
		return result;
	}

	private String queryData(String url) {
		try {
			if (null == StaticConstants.cookies) {
				ChromeBrowser chrome = new ChromeBrowser();
				StaticConstants.cookies = chrome.getCookiesFromFile(cookiesPath);
			}
			Connection connection = Jsoup.connect(url);
			connection.timeout(1000 * 20);
			connection.maxBodySize(0);// 不限长度
			connection.ignoreContentType(true);
			connection.header("User-Agent", StaticConstants.userAgent);
			connection.cookies(StaticConstants.cookies);
			Connection.Response res = connection.method(Connection.Method.GET).execute();
			return res.body();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
